
"use strict";
// Class definition

var districtAdd = function () {

    var eventHandler = function () {
        $(document).off('click', '.new-items');
        $(document).on('click', '.new-items', newItemHandle);

        $(document).off('click', '.btn-danger.close-btn');
        $(document).on('click', '.btn-danger.close-btn', removeItemHandle);

        $(document).off('click', '.btn-success.plus-btn');
        $(document).on('click', '.btn-success.plus-btn', addItemHandle);

        $(document).off('click', '.basic-configuration-form .clear-form');
        $(document).on('click', '.basic-configuration-form .clear-form', clearFormHandle);

        $('.regional-jobs-modal').on('show.bs.modal', initRegionalJobs);

        $(document).on('click', '.regional-jobs-modal .confirm', clickConfirm);

        $(document).off('changed.bs.select', '#checkItemTable select.table-select');
        $(document).on('changed.bs.select', '#checkItemTable select.table-select', changeTaleSelect);

        $(document).off('click', '.regional-jobs-modal label.k-checkbox');
        $(document).on('click', '.regional-jobs-modal label.k-checkbox', clickCheckbox);

        $(document).off('click', '[type="submit"]');
        $(document).on('click', '[type="submit"]', submitForm);
    };
    
    // Private functions
    var initCheckItemTable = function () {
        var data = [
            {
                "checkItemName": "A",
                "managePosition": ["1","2","3"],
                "checkStandard": "1"
            },
            {
                "checkItemName": "",
                "managePosition": ["1","4"],
                "checkStandard": "1"
            },
            {
                "checkItemName": "",
                "managePosition": ["1","3","4"],
                "checkStandard": "1"
            },
            {
                "checkItemName": "",
                "managePosition": ["1","4"],
                "checkStandard": "1"
            },
            {
                "checkItemName": "B",
                "managePosition": ["1","3","4"],
                "checkStandard": "1"
            },
            {
                "checkItemName": "C",
                "managePosition": ["1","3","4"],
                "checkStandard": "1"
            },
            {
                "checkItemName": "",
                "managePosition": ["1","3","4"],
                "checkStandard": "1"
            }
        ];
        $("#checkItemTable").DataTable({
            paging: false,
            searching: false,
            info: false,
            ordering: false,
            data: data,
            columns: [
                {data: 'checkItemName'},
                {data: 'managePosition'},
                {data: 'checkStandard'},
                {data: 'actions'},
            ],
            columnDefs: [
                {
                    targets: -1,
                    title: 'Actions',
                    orderable: false,
                    render: function(data, type, full, meta) {
                       var html = '';
                       html += '<button type="button" class="btn btn-danger close-btn btn-icon">'+
                            '<i class="la la-close k-font-light"></i>'+
                            '</button> <button type="button" class="btn btn-success plus-btn btn-icon">'+
                            '<i class="la la-plus k-font-light"></i>'+
                            '</button>';
                       return html;
                    },
                },
                {
                    targets: 0,
                    orderable: false,
                    render: function(data, type, full, meta) {
                        if(data !== '') {
                            return '<textarea type="text" placeholder="请输入..." style="resize: none;" class="form-control">'+ data +'</textarea>';
                        } else {
                            return '';
                        }
                    }
                },
                {
                    targets: 1,
                    orderable: false,
                    render: function(data, type, full, meta) {
                        return '<select class="form-control k_selectpicker table-select" multiple data-width="100%" data-value="[' + data +']" title="一 选择岗位 一">' +
                            '</select>';
                    }
                },
                {
                    targets: 2,
                    orderable: false,
                    render: function(data, type, full, meta) {
                        return '<input type="text" placeholder="请输入..." value="' + data + '" class="form-control">';
                    }
                }
            ]
        });

        $('.k_selectpicker').selectpicker();
        initMergeTable();
        getSelectOption();
    };

    /**
     * 初始化表格之后合并表格方法
     */
    var initMergeTable = function() {
        var trGroups = $("#checkItemTable").find('tbody tr');
        var targetTr;
        var mergeNum;
        trGroups.each(function (index, tr) {
            if ($(tr).find('textarea').length !== 0) {
                mergeNum = 1;
                targetTr = $(tr);
                if($(tr).next().length !== 0 && $(tr).next().find('textarea').length === 0) {
                    $(tr).addClass('hasMerge');
                }
            } else {
                mergeNum +=1;
                targetTr.find('td:first').attr('rowspan', mergeNum);
                targetTr.find('textarea').css('height', 'calc(' + (2.8*mergeNum + 0.5*(mergeNum-1)) + 'rem + '+ 2*mergeNum+'px)');
                $(tr).addClass('merge-tr');
                $(tr).prev().addClass('hasMerge');
            }
        });
    };

    var newItemHandle = function() {
        var content = {};
        var source = $("#check-item-template").html();
        var template = Handlebars.compile(source);
        var templateHtml = template(content);
        $("#checkItemTable tbody").append(templateHtml);
        var data = $("#checkItemTable").data('totalData') || [];
        setTableSelectOption(data);
    };

    var removeItemHandle = function() {
        var noMergeTr;
        if($(this).parents('tr').hasClass('merge-tr')) {
            noMergeTr = $($(this).parents('tr').prevAll(':not(.merge-tr)')[0]).find('td:first');
        } else {
            noMergeTr = $(this).parents('tr').find('td:first');
        }
        var rowspan = noMergeTr.attr('rowspan');
        if (rowspan) {
            rowspan = JSON.parse(rowspan) - 1;
        } else {
            rowspan = 1;
        }
        if ($(this).parents('tr').hasClass('merge-tr')) {
            noMergeTr.attr('rowspan', rowspan);
        }
        noMergeTr.find('textarea').css('height', 'calc(' + (2.8*rowspan + 0.5*(rowspan-1)) + 'rem + '+ 2*rowspan+'px)');
        if (rowspan === 1) {
            noMergeTr.parents('tr').removeClass('hasMerge');
        }
        var nextMergeTr = noMergeTr.parents('tr').next();
        if (!$(this).parents('tr').hasClass('merge-tr') && nextMergeTr.hasClass('merge-tr')) {
            nextMergeTr.find('td:first').attr('rowspan', rowspan);
            nextMergeTr.find('td:first').html(noMergeTr.html());
            nextMergeTr.find('td:first').find('textarea').val(noMergeTr.find('textarea').val());
            nextMergeTr.removeClass('merge-tr').addClass('hasMerge');
        }
        if (!nextMergeTr.next().hasClass('merge-tr')) {
            nextMergeTr.removeClass('hasMerge');
        }
        if(!$(this).parents('tr').hasClass('hasMerge')) {
            $(this).parents('tr').prev().removeClass('hasMerge');
        }
        $(this).parents('tr').remove();
    };

    var addItemHandle = function() {
        var content = {};
        var source = $("#names-standards-template").html();
        var template = Handlebars.compile(source);
        var templateHtml = template(content);
        $(this).parents('tr').addClass('hasMerge');
        $(this).parents('tr').after(templateHtml);
        var noMergeTr;
        if($(this).parents('tr').hasClass('merge-tr')) {
            noMergeTr = $($(this).parents('tr').prevAll(':not(.merge-tr)')[0]).find('td:first');
        } else {
            noMergeTr = $(this).parents('tr').find('td:first');
        }
        var rowspan = noMergeTr.attr('rowspan');
        if (rowspan) {
            rowspan = JSON.parse(rowspan) + 1;
        } else {
            rowspan = 2;
        }
        noMergeTr.attr('rowspan',rowspan);
        noMergeTr.find('textarea').css('height', 'calc(' + (2.8*rowspan + 0.5*(rowspan-1)) + 'rem + '+ 2*rowspan+'px)');
        noMergeTr.parents('tr').addClass('hasMerge');
        var data = $("#checkItemTable").data('totalData') || [];
        setTableSelectOption(data);
    };

    var clearFormHandle = function() {
        $(".basic-configuration-form").clearForm();
        $('.k_selectpicker').selectpicker('val', '');
    };

    /**
     * 初始化区域岗位
     * @param e
     */
    var initRegionalJobs = function (e) {
        $(this).data('relatedTarget', e.relatedTarget);
        $.ajax({
            type: 'GET',
            dataType: "json",
            timeout: 10000,
            url: 'json/regional-jobs-modal.json',
            data: {}
        }).done(function (resultData, textStatus, jqXHR) {
            toastr.success('成功!');
            $('.regional-jobs-modal .k-form .k-scroll').empty();
            resultData.forEach(function (item) {
                setRegionalJobsItem(item.label, item.value);
            });

            // 回显 //
            echoCheckedItem(e.relatedTarget);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            if (textStatus === 'timeout') {
                toastr.error('连接超时!');
            } else {
            }
            toastr.error('请求失败!');
            console.error(errorThrown);
        }).always(function () {

        });
    };

    /**
     * 设置区域岗位的选项。
     * @param label
     * @param value
     */
    var setRegionalJobsItem = function (label, value) {
        var formItemHtml = '';
        label = label || '';
        value = value || '';

        formItemHtml += '<div class="col-md-4 col-lg-3">';
        formItemHtml += '<div class="k-form__item">';
        formItemHtml += '<div class="k-checkbox-inline">';
        formItemHtml += '<label class="k-checkbox k-checkbox--bold k-checkbox--brand">';
        formItemHtml += '<input type="checkbox" value="' + value + '">' + label;
        formItemHtml += '<span></span>';
        formItemHtml += '</label>';
        formItemHtml += '</div>';
        formItemHtml += '</div>';
        formItemHtml += '</div>';

        $('.k-scroll').append(formItemHtml);
    };

    /**
     * 点击区域岗位的确认事件
     */
    var clickConfirm = function () {
        var $modal = $(this).parents('.modal');
        var targetBtn = $modal.data('relatedTarget');
        var $checkBox = $modal.find('.k-checkbox');
        var tableSelects = $("#checkItemTable select.table-select");
        var checkedElVal = [];
        var checkedElName = [];
        var data1 = [];
        var totalData = [];
        var selectIds = [];
        var dataValue;
        var isOk = true;
        $checkBox.each(function (i, checkItem) {
            var value = '';
            var label = '';
            if ($(checkItem).find('input:checked').prop('checked')) {
                value = $(checkItem).find('input:checked').val();
                label = $(checkItem).text();
                checkedElName.push(label);
                data1.push(value);
                checkedElVal.push({
                    value: value,
                    label: label
                });
            }
        });
        if ($(targetBtn).parent().siblings('input.input-hidden').attr('name') === 'regionalResponsiblePost') {
            dataValue = $('[name="regionalManagePosition"]').val();
        } else {
            dataValue = $('[name="regionalResponsiblePost"]').val();
        }
        dataValue = dataValue.length !== 0 ? JSON.parse(decodeURI(dataValue)) : [];
        mergeArr(dataValue, checkedElVal);
        dataValue.forEach(function(data) {
            totalData.push(data.value);
        });
        tableSelects.each(function (i, item) {
            var selectValues = $(item).val();
            selectValues.forEach(function (value) {
                if (selectIds.indexOf(value) === -1) {
                    selectIds.push(value);
                }
            });
        });
        selectIds.some(function(value) {
            if (totalData.indexOf(value) === -1) {
                isOk = false;
            }
        });
        if(!isOk) {
            swal({
                title: '清除的岗位中含有表格已选中的管理岗位',
                text: "您确定要清除此岗位吗？",
                type: 'warning',
                showCancelButton: true
            }).then(function(result) {
                if (result.value) {
                    $(targetBtn).parent().siblings('input.input-hidden').val(encodeURI(JSON.stringify(checkedElVal)));
                    $(targetBtn).parent().siblings('input[type="text"]').val(checkedElName).attr('title', checkedElName);
                    $modal.modal('hide');
                    getSelectOption();
                }
            });
            return;
        }
        $(targetBtn).parent().siblings('input.input-hidden').val(encodeURI(JSON.stringify(checkedElVal)));
        $(targetBtn).parent().siblings('input[type="text"]').val(checkedElName).attr('title', checkedElName);
        $modal.modal('hide');
        getSelectOption();
    };

    /**
     * 打开模态框的回显
     */
    var echoCheckedItem = function (targetBtn) {
        var checkedElVal = $(targetBtn).parent().siblings('input.input-hidden').val();
        if (checkedElVal.length !== 0) {
            checkedElVal = JSON.parse(decodeURI(checkedElVal));
            var modalClass = $(targetBtn).attr('data-target');
            checkedElVal.forEach(function (item) {
                var targetInput = $(modalClass).find('.k-checkbox input[value="' + item.value + '"]');
                targetInput.prop('checked', true);
            });
        }
    };

    /**
     * 获取区域岗位重组options数据
     */
    var getSelectOption = function() {
        var checkedElVal1 = $('[name="regionalResponsiblePost"]').val();
        var checkedElVal2 = $('[name="regionalManagePosition"]').val();
        var data1 = checkedElVal1.length !== 0 ? JSON.parse(decodeURI(checkedElVal1)) : [];
        var data2 = checkedElVal2.length !== 0 ? JSON.parse(decodeURI(checkedElVal2)) : [];
        mergeArr(data1, data2);
        $("#checkItemTable").data('totalData', data1);
        setTableSelectOption(data1);
    };

    /**
     * 合并2个数组，去重
     * data
     */
    var mergeArr = function (data1, data2) {
        var length1 = data1.length;
        var length2 = data2.length;
        for (var i = 0; i < length1; i++) {
            for (var j = 0; j < length2; j++) {
                //判断添加的数组是否为空了
                if (data1.length > 0) {
                    if (data1[i] && data1[i]["value"] === data2[j]["value"]) {
                        data1.splice(i, 1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
                        length1--;
                    }
                }
            }
        }
        for (var n = 0; n < data2.length; n++) {
            data1.push(data2[n]);
        }
        return data1;
    };

    /**
     * 给table中的select添加option
     * data
     */
    var setTableSelectOption = function (data) {
        var html = '';
        data.forEach(function (item) {
            html += '<option value="' + item.value + '">' + item.label + '</option>';
        });
        var tableSelects = $("#checkItemTable select.table-select");
        tableSelects.html('').append(html).selectpicker('refresh');
        tableSelects.each(function (i, item) {
            var tdValues = $(item).data('value') || [];
            $(item).selectpicker('val', tdValues);
        });

    };

    /**
     * 将table中的select值存起来
     */
    var changeTaleSelect = function () {
        $(this).data('value',$(this).val());
    };


    /**
     * 区域负责岗位单选控制
     */
    var clickCheckbox = function () {
        var $modal = $(".regional-jobs-modal");
        var targetBtn = $modal.data('relatedTarget');
        if ($(targetBtn).hasClass('responsible')) {
            $modal.find('.k-checkbox input').prop('checked', false);
            $(this).find('input').prop('checked', true);
        }
    };


    /**
     * 获取表格数据
     */
    var submitForm = function () {
        var trs = $("#checkItemTable").find('tbody tr');
        var tableData = [];
        var columns = ['checkItemName', 'managePosition', 'checkStandard'];
        //获取表格中要提交的数据
        tableMergeCell.getTableData(trs, tableData, columns);
    };

    return {
        // public functions
        init: function() {
            eventHandler();
            initCheckItemTable();
        }
    };
}();

jQuery(document).ready(function() {
    districtAdd.init();
});